// chat/chat_api.go
package chat

import (
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/websocket"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type ChatApi struct{}

// GetChatHistory 获取聊天记录
func (s *ChatApi) GetChatHistory(c *gin.Context) {
	userIDStr := c.Query("sender_id")
	receiverIDStr := c.Query("receiver_id")
	// 验证 user_id 和 receiver_id 参数
	if userIDStr == "" || receiverIDStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "user_id and receiver_id are required"})
		return
	}

	// 转换 user_id 和 receiver_id 为整数
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user_id format"})
		return
	}

	receiverID, err := strconv.Atoi(receiverIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid receiver_id format"})
		return
	}
	messages, err := chatService.GetChatHistory(userID, receiverID)
	if err != nil {
		response.FailWithMessage("获取聊天记录失败:"+err.Error(), c)
		return
	}
	response.OkWithData(messages, c)
}

// WebSocketHandler 处理 WebSocket 连接
func (s *ChatApi) WebSocketHandler(c *gin.Context) {
	userIDStr := c.Query("user_id")
	receiverIDStr := c.Query("receiver_id")

	// 验证 user_id 参数
	if userIDStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "user_id is required"})
		return
	}

	// 转换 user_id 为整数
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user_id format"})
		return
	}

	// receiverID 可选，若存在则转换为整数
	var receiverID int
	if receiverIDStr != "" {
		receiverID, err = strconv.Atoi(receiverIDStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid receiver_id format"})
			return
		}
	} else {
		receiverID = 0 // 表示没有指定接收者
	}

	// 调用 WebSocket 服务
	websocket.ServeWs(c.Writer, c.Request, userID, receiverID, websocket.GlobalHub)
}
